package com.ww.algorithm.question.list.reverse;

public class ListReverse {

    private static void reverse(LNode<Integer> head) {
        if (null == head || null == head.getNext()) {
            return;
        }

        // 前驱节点
        LNode<Integer> pre = null;
        // 当前节点
        LNode<Integer> cur = null;
        // 后继节点
        LNode<Integer> next = null;

        // 把链表首节点变为为尾结点
        cur = head.getNext();
        next = cur.getNext();
        cur.setNext(null);
        pre = cur;
        cur = next;

        while (null != cur.getNext()) {
            next = cur.getNext();
            cur.setNext(pre);
            pre = cur;
            cur = next;
        }

        // 结点最后一个结点指向倒数第二个结点
        cur.setNext(pre);
        // 链表的头结点指向原来链表的尾结点
        head.setNext(cur);
    }

    public static void main(String[] args) {
        LNode<Integer> head = new LNode<>();
        head.setNext(null);
        LNode<Integer> tmp = null;
        LNode<Integer> cur = head;
        for (int i = 0; i < 8; i++) {
            tmp = new LNode<>();
            tmp.setData(i);
            tmp.setNext(null);
            cur.setNext(tmp);
            cur = tmp;
        }
        System.out.println("逆序前：");
        for (cur = head.getNext(); cur != null; cur = cur.getNext()) {
            System.out.print(cur.getData() + " ");
        }
        System.out.println("\n逆序后");
        reverse(head);
        for (cur = head.getNext(); cur != null; cur = cur.getNext()) {
            System.out.print(cur.getData() + " ");
        }
    }
}
